package Inet;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

//客户端
public class UdpEchoClient_Dic {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public UdpEchoClient_Dic(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();

        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);

        while (true) {
            //1、控制台读取用户输入
            System.out.println("请输入要查询的单词->");
            String request = scanner.next();
            //2、构造请求并发送请求
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                                                                InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);

            //3、读取响应请求
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);

            //4、显示响应到控制台上
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println("该单词的释义为->");
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient_Dic dic = new UdpEchoClient_Dic("127.0.0.1",1010);
        dic.start();
    }
}
